package com.qq.weixin.mp.message.hxexp.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hxexp.weixin.common.web.HttpUtil;
import com.hxexp.weixin.constant.StringConstant;
import com.qq.weixin.constant.AppDevConstant;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.qq.weixin.mp.message.hxexp.service.MessageService;

/**
 * 接收微信消息和事件的controller
 * @author li.jiang
 *
 */
@Controller
@RequestMapping(value="/hxmsg")
public final class MessageController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageController.class);
    private static final String ENCRYPT_TYPE_AES = "aes";
    @Autowired
    private MessageService messageService;

    /**
     * 接收并回复微信服务器发送过来的消息或事件
     *
     * @param signature
     *            微信加密签名
     * @param msgSignature
     *            消息体签名
     * @param timestamp
     *            时间戳
     * @param nonce
     *            随机数
     * @param echostr
     *            随机字符串
     * @param encryptType
     *            加密类型（raw,aes）
     * @param request
     *            http请求
     * @return 文本字符串或XML格式文本
     * @see <a href="http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html">接入微信公众平台开发</a>
     * @see <a href="http://mp.weixin.qq.com/wiki/0/61c3a8b9d50ac74f18bdf2e54ddfc4e0.html">接入加解密</a>
     */
    @RequestMapping(value="/replymp", produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String handleMessage(@RequestParam(value = "signature", defaultValue = "") String signature,
                                @RequestParam(value = "msg_signature", defaultValue = "") String msgSignature,
                                @RequestParam(value = "timestamp", defaultValue = "") String timestamp,
                                @RequestParam(value = "nonce", defaultValue = "") String nonce,
                                @RequestParam(value = "echostr", defaultValue = "") String echostr,
                                @RequestParam(value = "encrypt_type", defaultValue = "") String encryptType, HttpServletRequest request) {

        LOGGER.debug("signature: {}", signature);
        LOGGER.debug("msg_signature: {}", msgSignature);
        LOGGER.debug("timestamp: {}", timestamp);
        LOGGER.debug("nonce: {}", nonce);
        LOGGER.debug("echostr: {}", echostr);
        LOGGER.debug("encrypt_type: {}", encryptType);
        LOGGER.debug("查询字符串：{}", request.getQueryString());

        // 验证请求，确认请求来自微信服务器
        String verifyResult = messageService.verifyURL(signature, AppDevConstant.HxExp.TOKEN, timestamp, nonce, echostr);
        if (!StringConstant.SUCCESS.equals(verifyResult)) {
            return verifyResult;
        }
        // 获取从微信服务器POST过来的消息
        String xmlstr = HttpUtil.getStringBody(request);
        if (!xmlstr.equals(StringConstant.BLANK)) {
            try {
                return replyMessage(xmlstr, encryptType, msgSignature, timestamp, nonce); // 回复用户消息
            } catch (Exception e) {
                LOGGER.error("回复用户消息时发生异常！", e);
            }
        }
        return "";
    }

    /**
     * 回复用户消息
     *
     * @param userMsg
     *            接收到的用户消息
     * @param encryptType
     *            加密类型（raw,aes）
     * @param msgSignature
     *            消息体签名
     * @param timestamp
     *            时间戳
     * @param nonce
     *            随机数
     * @return 回复给用户的消息
     * @throws IOException
     * @throws JAXBException
     * @throws AesException
     */
    private String replyMessage(String userMsg, String encryptType, String msgSignature, String timestamp, String nonce)
            throws IOException, JAXBException, AesException {
        // 在安全模式或兼容模式下，对收到的消息进行解密，回复的消息进行加密
        if (ENCRYPT_TYPE_AES.equals(encryptType)) {
            WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(AppDevConstant.HxExp.TOKEN,
                    AppDevConstant.HxExp.ENCODING_AESKEY, AppDevConstant.HxExp.APPID);
            // 解密消息内容
            String xmlMsg = wxBizMsgCrypt.decryptMsg(msgSignature, timestamp, nonce, userMsg);
            LOGGER.debug("解密后的XML消息体:\n{}", xmlMsg);
            // 消息处理
            String replyXml = messageService.messaging(xmlMsg.trim());
            if(StringConstant.BLANK.equals(replyXml)) {
                return StringConstant.BLANK;
            }
            // 加密消息
            String ciphertext = wxBizMsgCrypt.encryptMsg(replyXml, timestamp, nonce);
            LOGGER.debug("密文回复内容:\n{}", ciphertext);
            return ciphertext;
        } else {
            // 明文模式
            return messageService.messaging(userMsg.trim());
        }
    }
}
